package com.marvels.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.exception.MarvelsBusinessException;

/**marvels系统工具类
 * @author 何杰
 * 2018年4月3日
 */
public class MarvelsUtils {
	/**获取UUID
	 * @return
	 */
	public static String getUUID(){
		return String.valueOf(UUID.randomUUID());
	}
	
	/**通过UUID生成CODE
	 * @return
	 */
	public static String generateUUIDCode(){
		return getUUID().replace("-", "");
	}
	
	/**通过UUID生成CODE,带特殊凭证
	 * @return
	 */
	public static String generateUUIDCode(String sign){
		return sign+generateUUIDCode();
	}
	
	/**
	 *  文件流转文件  
	 * @param src 输入文件流
	 * @param dst  输出文件
	 * @throws IOException 
	 */
    public static void streamToFile(InputStream src, File dst) throws IOException {      
        InputStream in = null;      
        OutputStream out = null;      
        try {      
            in = new BufferedInputStream(src);      
            out = new BufferedOutputStream(new FileOutputStream(dst));      
            byte[] buffer = new byte[1024*10];      
            while (in.read(buffer) > 0) {      
                out.write(buffer);      
            }      
            out.flush();
        } finally {
            if (null != in) {      
                in.close();      
            }      
            if (null != out) {      
                out.close();      
            }      
        }      
    } 
    
    /**
     * 生成文件前缀   
     * @return
     */
	public static String getPathPrefix(){
		Calendar calendar = Calendar.getInstance();
	    int day = calendar.get(Calendar.DATE);
	    int month = calendar.get(Calendar.MONTH) + 1;
	    int year = calendar.get(Calendar.YEAR);
		StringBuffer prefix = new StringBuffer();
		prefix.append("/")
			  .append(year)
			  .append("/")
			  .append(month)
			  .append("/")
			  .append(day).append("/");
		return prefix.toString();
	}
	
	/**
	 * 获取请求IP地址.
	 *
	 * @param request
	 *            HTTP请求.
	 * @param response
	 *            HTTP响应.
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-real-ip");//先从nginx自定义配置获取 
		if(ip == null || ip.length() == 0 || MarvelsConstant.UNKNOWN.equalsIgnoreCase(ip)){
			ip = request.getHeader("x-forwarded-for");
			if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
	            //多次反向代理后会有多个ip值，第一个ip才是真实ip
	            int index = ip.indexOf(",");
	            if (index != -1) {
	                return ip.substring(0, index);
	            } else {
	                return ip;
	            }
			}
		}
		if (ip == null || ip.length() == 0 || MarvelsConstant.UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || MarvelsConstant.UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if ("0:0:0:0:0:0:0:1".equals(ip)) {
			try {
				ip = InetAddress.getLocalHost().getHostAddress();
			} catch (UnknownHostException e) {
				ip = MarvelsConstant.DEFAULT_IP_ADDRESS;
			}
		}
		return ip;
	}
}
